package com.xxgc.spring.interceptor;

import com.xxgc.spring.bean.Users;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;

//登录权限拦截判断
public class LoginInterceptor implements HandlerInterceptor {
    //抽取全局变量快捷键ctrl + alt + f
    private long time2;

    //让文件上传功能登录之后才能执行
    //在目标方法之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //时间2
        time2 = new Date().getTime();

        int status = response.getStatus();
        System.out.println("目标方法之前状态码 = " + status);

        return true;
    }
    //在目标方法之后执行，在试图对象返回之前执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HttpSession session = request.getSession();
        Users users = (Users) session.getAttribute("users");
        if(users == null){
            modelAndView.setViewName("userlogin.jsp");
        }
        System.out.println("111 = " + 111);

        int status = response.getStatus();
        System.out.println("目标方法之后状态码 = " + status);
    }
    //在流程都执行完毕过后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HttpSession session = request.getSession();
        Users users = (Users) session.getAttribute("users");
        //时间3
        long time3 = new Date().getTime();
        long time = time3 - time2;
        String servletPath = request.getServletPath();
        int status = response.getStatus();

        if(users == null){
            System.out.println("请求接口 = " + servletPath);
            System.out.println("请求耗时 = "+time+"毫秒");
            System.out.println("执行完毕状态码 = " + status);
        }else{
            //当前用户信息
            System.out.println("当前用户信息 = " + users);
            System.out.println("请求接口 = " + servletPath);
            System.out.println("请求耗时 = "+time+"毫秒");
            System.out.println("状态码 = " + status);
        }




        //支付宝 蜜罐

        //40%  60%（爬虫）益虫 害虫
        //调用Service层
    }
}
